document.getElementById('startPicking').addEventListener('click', () => {
  chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
    chrome.scripting.executeScript({
      target: { tabId: tabs[0].id },
      func: startPicking
    });
  });
});

document.getElementById('stopPicking').addEventListener('click', () => {
  chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
    chrome.scripting.executeScript({
      target: { tabId: tabs[0].id },
      func: stopPicking
    });
  });
});

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type === 'elementPicked') {
    const elementInfo = message.element;
    document.getElementById('pickedElement').innerText = JSON.stringify(elementInfo, null, 2);
  }
});

function startPicking() {
  document.addEventListener('click', handleElementPick, true);
}

function stopPicking() {
  document.removeEventListener('click', handleElementPick, true);
}

function handleElementPick(event) {
  event.preventDefault();
  event.stopPropagation();

  const element = event.target;
  element.style.outline = '2px solid red';

  const elementInfo = {
    tagName: element.tagName,
    id: element.id,
    classList: Array.from(element.classList),
    innerText: element.innerText
  };

  chrome.runtime.sendMessage({ type: 'elementPicked', element: elementInfo });
}
